package com.czkj.hwz.decorate.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.czkj.hwz.decorate.Activity.ClassifyActivity3;
import com.czkj.hwz.decorate.Activity.HomeDecorationActivity;
import com.czkj.hwz.decorate.Activity.SearchActivity;
import com.czkj.hwz.decorate.Activity.SelectActivity;
import com.czkj.hwz.decorate.Activity.SupervisorActivity;
import com.czkj.hwz.decorate.Activity.WorkerClassifyActivity;
import com.czkj.hwz.decorate.IMP.HttpDoImp;
import com.czkj.hwz.decorate.IMP.LocaitonImp;
import com.czkj.hwz.decorate.MyApp;
import com.czkj.hwz.decorate.R;
import com.czkj.hwz.decorate.base.BaseFragment;
import com.czkj.hwz.decorate.base.HttpUrl;
import com.czkj.hwz.decorate.base.TabEntity;
import com.czkj.hwz.decorate.bean.Enterprise;
import com.czkj.hwz.decorate.bean.Goods;
import com.czkj.hwz.decorate.bean.WorkerType;
import com.czkj.hwz.decorate.control.IndexGet;
import com.czkj.hwz.decorate.utils.ActivityUtils;
import com.czkj.hwz.decorate.view.banner.BannerView;
import com.czkj.hwz.decorate.view.banner.CustomViewPager;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.finalteam.okhttpfinal.HttpCycleContext;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.JsonHttpRequestCallback;
import cn.finalteam.okhttpfinal.RequestParams;
import okhttp3.Headers;

@ContentView(R.layout.fragment_frist)
public class FristFragment extends BaseFragment implements HttpDoImp, LocaitonImp, View.OnClickListener, HttpCycleContext {
    private static final String TAG = "FristFragment";
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    protected final String HTTP_TASK_KEY = "HttpTaskKey_" + hashCode();
    private List<WorkerType> workerTypeLists;
    private String mParam1;
    private String mParam2;
    private IndexGet mIndexGet = null;
    private ActivityUtils mActivityUtils;
    @ViewInject(R.id.banner)
    BannerView mBanner;
    @ViewInject(R.id.tb)
    SlidingTabLayout tb;
    @ViewInject(R.id.vp)
    CustomViewPager vp;
    @ViewInject(R.id.main_title)
    TextView main_title;
    @ViewInject(R.id.iv_classfy)
    ImageView iv_classfy;
    @ViewInject(R.id.iv_search)
    ImageView iv_search;
    @ViewInject(R.id.Appointment_supervision)
    ImageView appointment_supervision;
    @ViewInject(R.id.iv_team)
    ImageView iv_team;
    @ViewInject(R.id.iv_company)
    ImageView iv_company;
    private List<View> viewList;


    private LocationManager locationManager;
    private Context mContext;
    LocationListener locationListener;
    Location location;
    public static final int RECODE = 10001;

    JSONObject areaInfo;
    ArrayList<Enterprise> mEnterprises;
    ArrayList<TabEntity> mTabEntities;
    ArrayList<Goods> mGoodses;
    String[] imgUrl;
    String[] mTitles;
    BaseFragment[] mFragments;
    MyPagerAdapter adapter;
    String imgUrlStr;

    public FristFragment() {
    }



    public static FristFragment newInstance(String param1, String param2) {
        FristFragment fragment = new FristFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mContext = getContext();
        workerTypeLists=new ArrayList<>();
    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        iv_classfy.setOnClickListener(this);
        iv_search.setOnClickListener(this);
        appointment_supervision.setOnClickListener(this);
        iv_team.setOnClickListener(this);
        main_title.setOnClickListener(this);
        iv_company.setOnClickListener(this);
    }

    //轮播图
    private void bannerViewUrl(String[] imgs) {
        viewList = new ArrayList<View>();
        for (int i = 0; i < imgs.length; i++) {
            final ImageView image = new ImageView(mContext);
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            //设置显示格式
            imgUrlStr = HttpUrl.BASE_URL + imgs[i];
            x.image().bind(image, imgUrlStr);
            viewList.add(image);
        }
        mBanner.startLoop(true);
        mBanner.setViewList(viewList);
    }

    @Override
    public void onSuccess(String flag, Object... objects) {
        switch (flag) {
            case "indexGet":
                areaInfo = (JSONObject) objects[0];
                main_title.setText(areaInfo.getString("street"));
                imgUrl = (String[]) objects[1];
                mEnterprises = (ArrayList<Enterprise>) objects[2];
                MyApp app = (MyApp) getActivity().getApplication();
                app.setmEnterpriseList(mEnterprises);
                mGoodses = (ArrayList<Goods>) objects[3];
                bannerViewUrl(imgUrl);
                if (mEnterprises != null) {
                    mTabEntities = new ArrayList<>();
                    mTitles = new String[mEnterprises.size()];
                    mFragments = new BaseFragment[mEnterprises.size()];
                    GoodsFragment.vp = vp;
                    for (int i = 0; i < mEnterprises.size(); i++) {
                        mTitles[i] = mEnterprises.get(i).toString();
                        mFragments[i] = GoodsFragment.newInstance(mEnterprises.get(i), i);
                    }
                    adapter = new MyPagerAdapter(getChildFragmentManager());
                    vp.setScrollble(false);
                    vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                            vp.resetHeight(position);
                        }
                        @Override
                        public void onPageSelected(int position) {
                        }
                        @Override
                        public void onPageScrollStateChanged(int state) {
                        }
                    });
                    vp.setOffscreenPageLimit(mEnterprises.size());
                    vp.setAdapter(adapter);
                    tb.setViewPager(vp);
                    vp.resetHeight(0);
                }
                break;
        }
    }

    @Override
    public void getLocationSuccess(Location mLocation) {

        mIndexGet = new IndexGet(mContext, this);
        mIndexGet.getIndex(location);
    }
    @Override
    public void onError(String errinfo) {
        ToastUtils.showLong(errinfo);
    }
    private boolean checkPermission() {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, RECODE);
            return false;
        } else {
            return true;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getGPSConfi(mContext);
        } else {
            Toast.makeText(mContext, "没有获取位置的权限", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 判断手机GPS是否开启
     *
     * @return
     */
    public boolean isOpen(Context context) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //通过GPS卫星定位,定位级别到街
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        //通过WLAN或者移动网络确定位置
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }
    /**
     * GPS功能已经打开-->根据GPS去获取经纬度
     */
    public void getGPSConfi(Context context) {
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
            }
            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
            }
            @Override
            public void onProviderEnabled(String s) {
                //当用户打开GPS
                if (checkPermission()) {
                    location = locationManager.getLastKnownLocation(s);
                    if (location != null) {
                        getLocationSuccess(location);
                        locationManager.removeUpdates(locationListener);
                        locationManager = null;
                    }
                }
            }
            @Override
            public void onProviderDisabled(String s) {
                Toast.makeText(mContext, "获取位置定位被关闭，请手动打开", Toast.LENGTH_LONG).show();
            }
        };
        if (checkPermission()) {
            if (isOpen(context)) {
                if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                } else {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                }
            } else {
                Toast.makeText(mContext, "GPS未打开", Toast.LENGTH_SHORT).show();
            }
        }
        if (location != null) {
            getLocationSuccess(location);
        } else {
            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            locationManager.removeUpdates(locationListener);
        } catch (Exception e) {

        }
    }

    /**
     *
     *   就是fragment专门加载数据的；
     */
    @Override
    protected void lazyLoad() {
        mIndexGet = new IndexGet(mContext, this);
        mIndexGet.getIndex(location);
        getWorkerTypeList();
    }
    private void getWorkerTypeList() {
        RequestParams params=new RequestParams(this);
        HttpRequest.get(HttpUrl.WORKER_TYPE,params,new JsonHttpRequestCallback(){
            @Override
            protected void onSuccess(JSONObject jsonObject) {
                super.onSuccess(jsonObject);
                parseTypelistJson(jsonObject);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
            }
        });
    }
    private void parseTypelistJson(JSONObject jsonObject) {
        workerTypeLists.clear();
        JSONArray jsonArray=jsonObject.getJSONArray("result");
        for (int i=0;i<jsonArray.size();i++) {
            JSONObject jsonObject1=jsonArray.getJSONObject(i);
            Gson gson=new Gson();
            WorkerType workType=gson.fromJson(jsonObject1.toJSONString(),WorkerType.class);
            Log.d(TAG, "parseJson: "+workType.toString());
            Log.d(TAG, "parseJson: "+workType.getId());
            workerTypeLists.add(workType);

        }
        if (workerTypeLists.get(0).getName().equals("全部工种")) {

        }else {
            WorkerType workerType=new WorkerType();
            workerType.setName("全部工种");
            workerType.setId(-1000);
            workerTypeLists.add(0,workerType);
        }
        MyApp myApp= (MyApp) getActivity().getApplication();
        myApp.setWorkerTypeLists(workerTypeLists);
    }
    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()){
            case R.id.iv_classfy:
                toOtherActivity(ClassifyActivity3.class);
                break;
            case R.id.iv_search:
                toOtherActivity(SearchActivity.class);
                break;
            case R.id.Appointment_supervision:
                intent=new Intent(getActivity(),SupervisorActivity.class);
                intent.putExtra("mEnterprises",mEnterprises);
                startActivity(intent);
                break;
            case R.id.iv_team:
                intent=new Intent(getActivity(),WorkerClassifyActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_company:
                intent=new Intent(getActivity(), HomeDecorationActivity.class);
                startActivity(intent);
                break;
            case R.id.main_title:
                intent=new Intent(getActivity(), SelectActivity.class);
                startActivityForResult(intent,200);
                break;
        }
    }

    @Override
    public String getHttpTaskKey() {
        return HTTP_TASK_KEY;
    }


    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            if (null == mFragments[position]) {
                mFragments[position] = GoodsFragment.newInstance(mEnterprises.get(position), position);
            }
            return mFragments[position];
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==2) {
            if (requestCode==200) {
                String cityName=data.getStringExtra("cityName");
                main_title.setText(cityName);
            }
        }
    }
}
